package rottenbren.dev.android.diary.util;

import java.io.File;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper {
	
	public DBOpenHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}
	
	/**
	 * 필요 테이블 생성
	 * ANIVERSARY_MST (기념일 정보)
	 * int _id
	 * type text
	 * int month
	 * int day
	 * boolean isHoliday
	 * varchar title
	 */
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE aniversary_mst (" +
					"_id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, month INTEGER, day INTEGER, isHoliday BOOLEAN, title TEXT" +
					");");
		
		String[] classPath = System.getProperty("java.class.path").split(";");
		String filePath = "";
		
		for(String path : classPath){
			File file = new File(path + "/rottenbren/dev/android/diary/model/initAniversary.xml");
			if(file.exists()){
				filePath = file.getAbsolutePath();
				break;
			}
		}
		
		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
		try {
			doc = builder.build(filePath);

			Element rootElement = doc.getRootElement();
			List children = rootElement.getChildren();
			
			for(Object obj : children){
				Element element = (Element)obj;
				ContentValues newValues = new ContentValues();
				newValues.put("type", element.getAttributeValue("type"));
				newValues.put("month", Integer.parseInt(element.getAttributeValue("month")));
				newValues.put("day", Integer.parseInt(element.getAttributeValue("day")));
				newValues.put("title", element.getAttributeValue("title"));
				newValues.put("isHoliday", Boolean.parseBoolean(element.getAttributeValue("isHoliday")));
				db.insert("aniversary_mst", null, newValues);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}
